import "./index.css"
import * as React from "react";
import Index from "./";
import EventsUtils from "../../utils/EventsUtils";
import CommonUtils from "../../utils/CommonUtils";
import PropTypes from "prop-types";

/**
 * 提示框盒子
 * props: {
 *     alerts: [{Alerts}] 提示框列表
 * }
 */
export default class AlertBox extends React.Component{
    static propTypes = {
        alerts: PropTypes.array
    };
    constructor(props){
        super(props);
        this.alerts = this.props.alerts || [];
        this.state = {
            alerts: this.alerts
        }
    }
    //装载完成事件
    componentDidMount(){
        EventsUtils.on(AlertBox.events.ALERT, this.onAlert.bind(this));
    }
    //添加提示框事件
    onAlert(alert){
        alert.key = CommonUtils.randomKey();
        this.alerts.push(alert);
        this.setState({alerts: this.alerts});
    }
    //关闭提示框事件
    alertCloseHandler(index){
        this.alerts.splice(index, 1);
        this.setState({alerts: this.alerts});
    }
    render(){
        return (
            <div
                ref={element=>this.container = element}
                style={{height: 4.15*this.state.alerts.length + "rem"}}
                className={"alertBox " + (this.props.className || "")}
            >
                {this.state.alerts.map((alert, index)=>
                    <Index
                        key={alert.key}
                        content={alert.content}
                        closable={alert.closable}
                        display={alert.display || true}
                        type={alert.type}
                        survivalTime={alert.survivalTime}
                        onClose={this.alertCloseHandler.bind(this, index)}/>
                )}
            </div>
        )
    }
}
/**
 * 事件列表
 * @type {{ALERT: string}}
 */
AlertBox.events = {
    //弹出提示框事件args: {Alert.props}
    ALERT: "leader.events.alert-box.alert"
};
Object.freeze(AlertBox.events);
